import setting from '../../settings'
import { getOemApi } from '../../api/oemApi'
import { getAppApi } from '../../api/appApi'
import { setAjaxURL } from '../../utils/request'
import { Notification } from 'element-ui'

const defaultOEM = { copyName: setting.copyName, copyRight: setting.copyRight, copyContact: setting.copyContact }
export default {
  state: {
    oem: defaultOEM,
    app: {},
    isExpand: false
  },
  mutations: {
    setOem: (state, data) => {
      state.oem = data || defaultOEM
    },
    setApp: (state, data) => {
      state.app = data
    },
    setExpand: (state, data) => {
      state.isExpand = data
    }
  },
  actions: {
    getOem: ({ commit }, params) => {
      return new Promise((resolve, reject) => {
        getOemApi().then(res => {
          commit('setOem', res.data.data.records && res.data.data.records[0])
          resolve(res.data.data.records)
        }).catch((error) => {
          const msg = error.response.data.msg || error.response.statusText || error.response.data.message || error.response.data
          console.error('获取应用信息异常:', msg)
          Notification.error({
            title: '服务异常',
            message: '获取应用信息异常，请联系管理员',
            duration: 0
          })
          reject(new Error('获取应用信息异常:' + msg))
        })
      })
    },
    getApp: ({ commit }, params) => {
      return new Promise((resolve, reject) => {
        getAppApi(params).then(res => {
          commit('setApp', res.data.data || {})
          if (res.data.data) {
            setAjaxURL(res.data.data)
            resolve(res.data.data)
          } else {
            console.error('未配置应用信息:', params)
            reject(new Error('未配置应用信息:' + params))
          }
        }).catch((error) => {
          const msg = error.response.data.msg || error.response.statusText || error.response.data.message || error.response.data
          console.error('获取应用信息异常:', msg)
          Notification.error({
            title: '服务异常',
            message: '获取应用信息异常，请联系管理员',
            duration: 0
          })
          reject(new Error('获取应用信息异常:' + msg))
        })
      })
    }
  }
}
